#include "../comm.h"
class Solution {
public:
    static constexpr int N = 15;
    int dist[N][N];
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    using PII = pair<int, int>;
    int n, m;

    int orangesRotting(vector<vector<int>>& grid) {
        memset(dist, -1, sizeof dist);
        queue<PII> q;
        n = grid.size(), m = grid[0].size();
        for(int i = 0; i < n; ++i)
            for(int j = 0;j < m; ++j)
                if(grid[i][j] == 2)
                    q.push({i, j}),
                    dist[i][j] = 0;

        
        while(q.size())
        {
            auto [x, y] = q.front();
            q.pop();
            int now = dist[x][y];
            for(int i = 0; i < 4; ++i)
            {
                int xx = x + dx[i], yy = y + dy[i];
                if(xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == -1 && grid[xx][yy] == 1)
                    dist[xx][yy] = now + 1, q.push({xx, yy}); 
            }
        }

        int mx = 0;
        for(int i = 0; i < n; ++i)
             for(int j = 0; j < m; ++j)
                if(grid[i][j] == 1 && dist[i][j] == -1)
                    return -1;
                else if(dist[i][j] != -1)
                    mx = max(mx, dist[i][j]);


        return mx;
    }
};